/**
 * 
 */
package com.liik.game;

import android.content.Context;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;


public class GameSurfaceView extends SurfaceView implements SurfaceHolder.Callback {

	private GameThread gameThread;
	private GestureDetector gestureDetector;

	public GameSurfaceView(Context context, ScreenHolder screenHolder) {
		super(context);
		getHolder().addCallback(this);
		gameThread = new GameThread(getHolder(), screenHolder);
		gestureDetector = new GestureDetector(gameThread);
		gestureDetector.setOnDoubleTapListener(gameThread);
		gestureDetector.setIsLongpressEnabled(false);
		setFocusable(true);
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		Log.i("SurfaceView", "surfaceCreated()");
		gameThread.setSurfaceHolder(holder);
		gameThread.setRunning(true);
		gameThread.start();
	}
	
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		Log.i("SurfaceView", "surfaceChanged()");
		gameThread.surfaceChanged(holder, format, width, height);
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		Log.i("SurfaceView", "surfaceDestroyed()");
		boolean retry = true;
		gameThread.setRunning(false);
		while (retry) {
			try {
				gameThread.join();
				retry = false;
			} catch (InterruptedException e) {
				// try again to shut down
			}
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_UP)
			gameThread.onUp(event);
		return gestureDetector.onTouchEvent(event);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return gameThread.onKeyDown(keyCode, event);
	}
	
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		return gameThread.onKeyUp(keyCode, event);
	}

	public GameThread getThread() {
		return gameThread;
	}
}
